//
//  MKAPITestHttpAPIBase.m
//  MKAPITests
//
//  Created by 苏尚进 on 2022/9/5.
//  Copyright © 2022 moon. All rights reserved.
//

#import "MKAPITestHttpAPIBase.h"
#import "MKAPITestHttpRequestAF.h"

@interface MKAPITestHttpAPIBase()
@end

@implementation MKAPITestHttpAPIBase

- (MKAPIHttpRequestType)requestType{
    return MKAPIHttpRequestTypeData;
}

- (void)doCancel{
    [super doCancel];
    if(self.waittingTasks.count){
        [self cancelWaittingTasks];
    }else{
        [self completeWithError:[NSError mkapi_errorWithCancelTask:self]];
    }
}

- (void)sendRequest:(MKAPIHttpRequestBase *)request withCompletion:(nullable MKAPIServiceRequestBlock)completion{
    if(self.state==MKAPITaskStateCreated){
        [self run];
    }
#ifdef DEBUG
    NSLog(@"send request:\n%@",[self requestDescriptionWithRequest:request requestParam:request.requestParam]);
#endif
    [self waitTask:request withCompletion:^(MKAPIHttpRequestBase * _Nullable requestTask, BOOL success, NSError * _Nullable error) {
#ifdef DEBUG
        NSLog(@"get response:\n%@",[self responseDescription:requestTask requestParam:request.requestParam respondData:requestTask.responseData error:error]);
#endif
        if(completion){
            completion(requestTask,success,error);
        }
    }];
}

- (NSString *)requestDescriptionWithRequest:(nullable __kindof MKAPIHttpRequestBase *)request requestParam:(nullable __kindof MKAPIRequestParam *)requestParam{
    NSString *desc = [request.class requestDescriptionWithRequest:request requestParam:requestParam customBlock:nil];
    return desc;
}

- (NSString *)responseDescription:(MKAPIHttpRequestBase *)request requestParam:(MKAPIRequestParam *)requestParam respondData:(id)responseData error:(NSError *)error{
    NSString *desc = [request.class responseDescriptionWithRequest:request requestParam:requestParam customBlock:nil];
    return desc;
}

- (void)sendRequestWithParam:(MKAPIRequestParam *)requestParam withCompletion:(nullable MKAPIServiceRequestBlock)completion{
    MKAPITestHttpRequestAF *requestTask = [[MKAPITestHttpRequestAF alloc] init];
    requestTask.requestParam = requestParam;
    requestTask.requestType = self.requestType;
    [self sendRequest:requestTask withCompletion:completion];
}
- (void)configCommonRequest:(MKAPIRequestParam *)requestParam path:(NSString *)path{
    NSString *domain = @"https://httpbingo.org";
    requestParam.url = [NSString stringWithFormat:@"%@%@",domain,path];
    requestParam.httpMethod = MKAPIHttpRequestMethodPOST;
}
@end
